<template>
  <div class="input-rules">
    <TagRender :tags="rules" :enable="!inputDisabled" @add="showPicker" @close="remove" />
    <ElementDialog height="400px" title="添加规则" :visible.sync="isDialogVisible">
      <PageableTable :api="getPage" hide-on-single-page @selection-change="selectionChange">
        <TableColumn label="规则名称" prop="name" />
        <TableColumn label="规则ID" prop="actorId" />
        <TableColumn label="规则类型" prop="actorType" />
        <TableColumn label="参数" prop="params" />
        <TableColumn label="是否远程调用" prop="remoteFlag" />
      </PageableTable>
      <template #footer>
        <ElButton type="primary" @click="confirm">确定</ElButton>
        <ElButton @click="isDialogVisible = false">取消</ElButton>
      </template>
    </ElementDialog>
  </div>
</template>

<script>
  import { getPage } from '@/api/admin/actoruser'
  export default {
    name: 'InputRules',
    inject: {
      elForm: {
        default: ''
      },
      elFormItem: {
        default: ''
      }
    },
    props: {
      value: Array,
      disabled: Boolean,
      preSelected: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        rules: [],
        selectedRows: [],
        isDialogVisible: false
      }
    },
    computed: {
      inputDisabled() {
        return this.disabled || (this.elForm || {}).disabled
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(newVal) {
          if (this.preSelected) {
            this.rules = [...(newVal || [])]
          }
        }
      }
    },
    methods: {
      selectionChange(rows) {
        this.selectedRows = rows
      },
      getPage(page) {
        return getPage({ current: page.page, size: page.limit })
      },
      showPicker() {
        this.isDialogVisible = true
      },
      remove(val) {
        this.emitInput(this.rules.filter(value => value.id !== val.id))
      },
      confirm() {
        this.emitInput(this.selectedRows)
        this.isDialogVisible = false
      },
      emitInput(val) {
        this.$emit('input', val)
      }
    }
  }
</script>
